package utils

import (
	"crypto/md5"
	"encoding/hex"
	"sort"
	"strings"

	"enterprise-wechat-pay-sdk/config"
)

// GenerateSign 生成签名
func GenerateSign(params map[string]string) string {
	// 1. 参数排序
	var keys []string
	for k := range params {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	// 2. 拼接字符串
	var builder strings.Builder
	for _, k := range keys {
		if params[k] != "" {
			builder.WriteString(k)
			builder.WriteString("=")
			builder.WriteString(params[k])
			builder.WriteString("&")
		}
	}
	builder.WriteString("key=")
	builder.WriteString(config.GlobalConfig.Wechat.APIKey)

	// 3. MD5加密
	hash := md5.New()
	hash.Write([]byte(builder.String()))
	return strings.ToUpper(hex.EncodeToString(hash.Sum(nil)))
}

// ValidateSign 验证签名
func ValidateSign(params map[string]string, sign string) bool {
	return GenerateSign(params) == sign
}

// FormatAmount 格式化金额（元转分）
func FormatAmount(amount float64) int {
	return int(amount * 100)
}

// ParseAmount 解析金额（分转元）
func ParseAmount(amount int) float64 {
	return float64(amount) / 100
}
